var express = require('express');
var router = express.Router();
const tableName = 'user'
const { Success, MError } = require("../utils/Result");
const Db = require("../utils/Db");
const crypto = require('crypto');
const random = require('string-random');
const { getUUID, getToken } = require("../utils");

//注册用户
router.post("/register", async(req, res) => {
    let { roleid, username, password, status } = req['body'];
    const info = await Db.select(req, `SELECT * FROM ${tableName} WHERE username = '${username}'`);
    if (info) {
        res.send(MError("用户名已存在，不能重复！"));
    } else {
        const randstr = random(5);
        password += randstr;
        password = crypto.createHash('md5').update(password).digest("hex");
        const result = await Db.insert(req, tableName, {
            uid: getUUID(),
            username,
            password,
            randstr,
            roleid,
            status
        });
        if (result) {
            res.send(Success([], "添加成功"));
        } else {
            res.send(MError("添加失败，请查看字段信息是否正确"));
        }
    }
});

//用户登录
router.post("/userlogin", async(req, res) => { // 登录接口
    let { username, password, roleid } = req['body'];
    if (!username || !password) {
        res.send(MError("请填写用户名和密码"));
        return;
    }
    const result = await Db.select(req, `SELECT * FROM ${tableName} WHERE  username = '${username}' && roleid = '${roleid}'`)
    if (result === null) {
        res.send(MError("用户信息不存在"));
        return;
    }
    const info = result[0];
    password += info.randstr;
    // console.log(password, info);
    password = crypto.createHash('md5').update(password).digest("hex");
    if (password !== info.password) {
        res.send(MError("用户名密码错误"));
        return;
    }

    delete info.password;
    delete info.randstr;
    info['token'] = getToken(info['uid']);
    res.send(Success(info, '登录成功'));
});

module.exports = router;